package com.sky.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录(小程序)
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User logion(UserLoginDTO userLoginDTO) {
        //1 实现微信登录，获取openid
        //1-1 url
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        //1-2 请求参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        //1-3 发起请求
        String json = HttpClientUtil.doGet(url, paramMap);
        //1-4 解析json
        Map<String,String> map = JSON.parseObject(json, Map.class);//{"session_key":"","openid":""}
        String openid = (String) map.get("openid");//openid就是用户在微信端对应的唯一标识
        //1-5 判断openid是否为空
        if(StrUtil.isEmpty(openid)){
            throw new RuntimeException("登录失败");
        }

        //2 根据openid查询数据库,查到了老用户,直接登录  没有查到  创建新用户
        User user = userMapper.findByOpenid(openid);

        //2-1 没有查到  创建新用户
        if(user == null){
            user = User.builder()//直接复用user
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(user);//主键返回   (user保存完以后,前端还需要id,所以)

        }
        //2-2 根据openid查询数据库,查到了老用户,直接(返回)
        return user;

    }
}
